package edu.uoc.tfc.gui.common;

import java.lang.reflect.Method;
import java.util.Iterator;

public class JSONDataTableInitializer {
	
	public static final void parseAndInitialize(Object object, String columnIdName) throws Exception {
		
		if (object instanceof Object[]) {
			
			Object[] arrayObject = (Object[]) object;
			for (int i = 0; i < arrayObject.length; i++) {
				if (arrayObject[i] instanceof JSONDataTableValueObject) {
					JSONDataTableValueObject jsonObject = (JSONDataTableValueObject) arrayObject[i];
					setRowId(jsonObject, columnIdName);
				}
			}
			
		} else if(object instanceof JSONDataTableResult){
			JSONDataTableResult datatableResult = (JSONDataTableResult) object;
			
			if (datatableResult.getElements() != null && datatableResult.getElements().size() > 0) {
				Iterator<JSONDataTableValueObject> iterElements = datatableResult.getElements().iterator();
				while (iterElements.hasNext()) {
					JSONDataTableValueObject jsonDataTableValueObject = 
						(JSONDataTableValueObject) iterElements.next();
					
					setRowId(jsonDataTableValueObject, columnIdName);
				}
			}
			
		} else {
			if (object instanceof JSONDataTableValueObject) {
				JSONDataTableValueObject jsonObject = (JSONDataTableValueObject) object;
				setRowId(jsonObject, columnIdName);
			}
		}
		
	}
	
	private static void setRowId(JSONDataTableValueObject jsonObject, String columnIdName) throws Exception {
		Method getter = getColumnIdGetter(jsonObject, columnIdName);
		Object returnValue = getter.invoke(jsonObject, new Object[]{});
		if (returnValue == null)
		{
			jsonObject.setDT_RowId("");
		}
		else
		{
			jsonObject.setDT_RowId(returnValue.toString());
		}
		jsonObject.setDT_RowClass("gradeA");
	}
	
	private static Method getColumnIdGetter(Object object, String columnIdName) {
		Method[] metodos = object.getClass().getMethods();
    	Method getter = null;
    	
    	for (int i = 0; i < metodos.length; i++) {
			if (metodos[i].getName().equalsIgnoreCase("get" + columnIdName)) {
				getter = metodos[i];
				break;
			}
		}
    	
    	return getter;
	}

}
